"""6.2.6 Ajout de cascade pour les ndd

Revision ID: 6d80ecf34a1a
Revises: 82443e7fc843
Create Date: 2021-06-24 19:48:48.232076

"""

# revision identifiers, used by Alembic.
revision = "6d80ecf34a1a"
down_revision = "82443e7fc843"

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from caerp.alembic import utils


def update_database_structure():
    for fix in ("", "km"):
        table = "expense%s_line" % fix
        for key in ("fk_expense%s_line_id" % fix, "expense%s_line_ibfk_1" % fix):
            if utils.foreign_key_exists(table, key):
                op.drop_constraint(op.f(key), table, type_="foreignkey")
                break

        op.create_foreign_key(
            op.f("fk_expense%s_line_id" % fix),
            table,
            "baseexpense_line",
            ["id"],
            ["id"],
            ondelete="CASCADE",
        )


def migrate_datas():
    from alembic.context import get_bind
    from zope.sqlalchemy import mark_changed
    from caerp_base.models.base import DBSESSION

    session = DBSESSION()
    conn = get_bind()

    mark_changed(session)
    session.flush()


def upgrade():
    update_database_structure()
    migrate_datas()


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
